<template>
	<view class="page">
		<view class="title">
			<view class="name">蜗牛学苑</view>
			<view>WoNiuXy.com</view>
		</view>
		<view class="container ">

			<!-- 标签页切换 -->
			<view class="tabs">
				<text :class="{ active: currentTab === 'login' }" @tap="switchTab('login')">登录</text>
				<text :class="{ active: currentTab === 'register' }" @tap="switchTab('register')">注册</text>
			</view>

			<!-- 登录表单 -->
			<view v-if="currentTab === 'login'" class="form">
				<input v-model="loginData.username" placeholder="请输入用户名" :disabled="loading" />
				<input v-model="loginData.password" type="password" placeholder="请输入密码" password :disabled="loading" />
				<button :loading="loading" :disabled="loading" class="primary-btn" @click="handleLogin">
					{{ loading ? '登录中...' : '登录' }}
				</button>
				<button class="auth-btn" :disabled="loading" open-type="getPhoneNumber"
					@getphonenumber="handlePhoneAuth">
					手机号码授权登录
				</button>
			</view>

			<!-- 注册表单 -->
			<view v-else class="form">
				<input v-model="registerData.username" placeholder="请输入用户名" :disabled="loading" />
				<input v-model="registerData.password" type="password" placeholder="请输入密码" password
					:disabled="loading" />
				<input v-model="registerData.phone" placeholder="请输入电话号码" type="number" :disabled="loading" />

				<view class="form-item">
					<text class="label">请选择角色：</text>
					<radio-group @change="handleRoleChange">
						<label class="radio-item" v-for="role in roles" :key="role.value">
							<radio :value="role.value" :checked="registerData.role === role.value"
								:disabled="loading" />
							{{ role.label }}
						</label>
					</radio-group>
				</view>

				<button :loading="loading" :disabled="loading" class="primary-btn" @click="handleRegister">
					{{ loading ? '注册中...' : '注册' }}
				</button>
			</view>

			<!-- 全局提示 -->
			<!-- <uni-popup v-if="true" ref="popup" type="message">
				<uni-popup-message :type="message.type" :message="message.text"></uni-popup-message>
			</uni-popup> -->
		</view>

	</view>
</template>

<script setup>
	import {
		reactive,
		ref
	} from 'vue';
	import {
		login,
		register,
		code1
	} from '@/pages/utils/api/UsersAPI.js';
	import {
		useUserStore
	} from '@/stores/api.js';
import { getCurrentInstance } from 'vue';
const { proxy } = getCurrentInstance();
	const userStore = useUserStore();

	// 响应式数据
	const currentTab = ref('login');
	const loading = ref(false);
	const message = reactive({
		type: 'success',
		text: ''
	});

	const roles = [{
			label: '学生',
			value: '学生'
		},
		{
			label: '教师',
			value: '老师'
		}
	];

	const loginData = reactive({
		username: '',
		password: ''
	});

	const registerData = reactive({
		username: '',
		password: '',
		role: '',
		phone: ''
	});

	const authData = reactive({
		code: '',
		encryptedData: '',
		iv: ''
	});
	const showMessage = (text, type = 'error') => {
		// message.text = text;
		// message.type = type;
		// proxy.$refs.popup.open(); // 正确访问$refs的方式
		 // 根据类型设置图标（支持 'success'、'loading'、'none'）
		  const icon = type === 'success' ? 'success' : 
		               type === 'loading' ? 'loading' : 'none';
		  
		  // 使用小程序原生弹窗
		  uni.showToast({
		    title: text,        // 显示的内容
		    icon: icon,         // 图标类型
		    duration: 3000,     // 显示时长（毫秒）
		    mask: true,         // 是否显示透明蒙层，防止触摸穿透
		    success: () => {
		      console.log('消息提示显示成功');
		    },
		    fail: (err) => {
		      console.error('消息提示显示失败:', err);
		    }
		  });
			
		};
			

	
	const validateLoginForm = () => {
		if (!loginData.username.trim()) {
			showMessage('请输入用户名');
			return false;
		}
		if (!loginData.password) {
			showMessage('请输入密码');
			return false;
		}
		return true;
	};

	const validateRegisterForm = () => {
		if (!registerData.username.trim()) {
			showMessage('请输入用户名');
			return false;
		}
		if (!registerData.password) {
			showMessage('请输入密码');
			return false;
		}
		if (!registerData.phone) {
			showMessage('请输入手机号');
			return false;
		}
		if (!/^1[3-9]\d{9}$/.test(registerData.phone)) {
			showMessage('请输入正确的手机号');
			return false;
		}
		if (!registerData.role) {
			showMessage('请选择角色');
			return false;
		}
		return true;
	};

	const handleLogin = async () => {
		if (!validateLoginForm()) return;

		loading.value = true;
		try {
			const res = await login(loginData);
			if (res.code === 200) {
				userStore.setUserInfo(res.data);
				uni.setStorageSync('userInfo', JSON.stringify(res.data));
				navigateToCenter();
			} else {
				showMessage(res.message || '登录失败');
			}
		} catch (error) {
			console.error('登录失败', error);
			showMessage('登录失败，请稍后重试');
		} finally {
			loading.value = false;
		}
	};

	const handleRegister = async () => {
		if (!validateRegisterForm()) return;

		loading.value = true;
		try {
			const res = await register(registerData);
			if (res.code === 200) {
				showMessage('注册成功', 'success');
				switchTab('login');
			} else {
				showMessage(res.message || '注册失败，该用户已存在！');
			}
		} catch (error) {
			console.error('注册失败', error);
			showMessage('注册失败，请稍后重试');
		} finally {
			loading.value = false;
		}
	};

	const handlePhoneAuth = (event) => {
		const {
			detail
		} = event;
		authData.encryptedData = detail.encryptedData;
		authData.iv = detail.iv;

		uni.login({
			provider: 'weixin',
			univerifyStyle: {
				fullScreen: true
			},
			success(res) {
				authData.code = res.code;
				handleAuthLogin();
			},
			fail(err) {
				showMessage('微信登录失败');
				console.error('微信登录失败', err);
			}
		});
	};

	const handleAuthLogin = async () => {
		loading.value = true;
		try {
			const res = await code1(authData);
			if (res.code === 577) {
				showMessage('用户不存在，请注册');
				switchTab('register');
			} else if (res.code === 200) {
				showMessage('登录成功', 'success');
				navigateToCenter();
			} else {
				showMessage(res.message || '授权登录失败');
			}
		} catch (error) {
			console.error('授权登录失败', error);
			showMessage('授权登录失败');
		} finally {
			loading.value = false;
		}
	};

	const navigateToCenter = () => {
		uni.switchTab({
			url: '/pages/main/index',
			success: () => console.log('跳转成功'),
			fail: (err) => {
				console.error('跳转失败:', err);
				showMessage('跳转失败');
			}
		});
	};

	const handleRoleChange = (e) => {
		registerData.role = e.detail.value;
	};

	const switchTab = (tab) => {
		currentTab.value = tab;
		// 清空表单
		if (tab === 'login') {
			Object.assign(loginData, {
				username: '',
				password: ''
			});
		} else {
			Object.assign(registerData, {
				username: '',
				password: '',
				phone: '',
				role: ''
			});
		}
	};
</script>

<style scoped lang="scss">
	.container {
		padding: 1.25rem;
		background-color: #f8f8f8;
		margin: auto;
		width: 77%;
		border-radius: 2.5%;
		position: absolute;
		top: 14%;
		right: 6%;
		height: fit-content;
	}

	.title {
		width: 100%;
		color: #ffffff !important;
		text-align: center;
		position: absolute;
	    top: 4%;
		.name{
			font-size:1.5rem;
		}
	}

	#app {
		height: 100%;
		min-height: 100vh;
		background: linear-gradient(135deg, #4e54c8, #8f94fb) !important;
	}

	.page {
		min-height: 100vh;
		background: linear-gradient(135deg, #4e54c8, #8f94fb) !important;
	}

	.tabs {
		display: flex;
		justify-content: center;
		margin-bottom: 60rpx;
		border-bottom: 1rpx solid #eee;
		border-radius: 62%;

		text {
			flex: 1;
			text-align: center;
			font-size: 32rpx;
			color: #666;
			padding: 20rpx 0;
			position: relative;

			&.active {
				color: #007AFF;
				font-weight: bold;

				&::after {
					content: '';
					position: absolute;
					bottom: 0;
					left: 50%;
					transform: translateX(-50%);
					width: 60%;
					height: 4rpx;
					background-color: #007AFF;
					border-radius: 2rpx;
				}
			}
		}
	}

	.form {
		background-color: #fff;
		padding: 40rpx;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

		input {
			height: 88rpx;
			padding: 0 24rpx;
			border: 1rpx solid #e5e5e5;
			border-radius: 8rpx;
			margin-bottom: 32rpx;
			font-size: 28rpx;
			background-color: #f9f9f9;

			&:focus {
				border-color: #007AFF;
			}
		}

		.form-item {
			margin-bottom: 32rpx;

			.label {
				display: block;
				margin-bottom: 16rpx;
				font-size: 28rpx;
				color: #333;
			}

			.radio-item {
				display: flex;
				align-items: center;
				margin-right: 40rpx;
				margin-bottom: 16rpx;
				font-size: 26rpx;
			}
		}
	}

	.primary-btn {
		background-color: #007AFF;
		color: white;
		height: 88rpx;
		line-height: 88rpx;
		font-size: 30rpx;
		border-radius: 44rpx;
		margin-bottom: 30rpx;

		&:active {
			opacity: 0.8;
		}

		&[disabled] {
			background-color: #a0cfff;
		}
	}

	.auth-btn {
		background-color: #07C160;
		color: white;
		height: 88rpx;
		line-height: 88rpx;
		font-size: 30rpx;
		border-radius: 44rpx;

		&:active {
			opacity: 0.8;
		}

		&[disabled] {
			background-color: #95d8a7;
		}
	}
</style>